import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './index'
import { initRouteAndNav } from '~/utils/util'

const whiteList = ['Login', 'Init', 'Clean']

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from) => {
  NProgress.start()
  const store = useAppStore()

  // 先判断有没有门店信息
  if ((to.name as string) != 'Init') {
    const shop = cache.getShop()
    if (!shop) {
      return '/init'
    }
  }

  if (whiteList.includes(to.name as string)) return

  // 初始化用户路由
  if (!store.user) {
    let redirect: string = ''
    try {
      const user = await apis.api.loginOauth()
      user && user.token ? store.initial(user) : (redirect = `/login?redirect=${to.fullPath}`)
    } catch (error) {
      redirect = `/login?redirect=${to.fullPath}`
    }
    if (redirect != '') return redirect
  }

  if (!store.initRoute) {
    // 初始化路由和菜单
    if (store.user) {
      const menus = initRouteAndNav(store.user.authorities)
      store.initMenu(menus)
      return to.fullPath
    }
  }
})

router.afterEach(() => NProgress.done())
